<template>
  <div>
    <Form :model="modelForm" class="ivu-form-no-margin-bottom" :rules="rule" :label-width="110">
      <Row :gutter="32" class="code-row-bg">
        <Col span="12">
          <!-- 组织名称 -->
          <Form-item prop="orgId" :label="$t('module.role.organizationName')">
            <Input v-model="orgName"  disabled />
          </Form-item>
        </Col>
        <Col span="12">
          <!-- 角色名称 -->
          <Form-item prop="roleId" :label="$t('module.role.roleName')">
            <Input v-model="roleName"  :disabled="isRoleDisabled" />
          </Form-item>
        </Col>
      </Row>

      <Row :gutter="32" class="code-row-bg">
        <Col span="12">
          <!-- 权限类型 必填-->
          <Form-item prop="managementType" :label="$t('module.role.accessType')">
            <Select
              v-model="modelForm.managementType"
              
              class="no-borderColor"
              :transfer="true"
              @on-change="handleSelectDataAccess"
              :disabled="readOnly"
            >
              <Option
                v-for="items in managementTypeList"
                :value="items.vsiKey"
                :key="items.vsiKey"
              >{{ items.vsiValue }}</Option>
            </Select>
          </Form-item>

          <!-- 部分子组织: 显示tree -->
          <div class="org-tree-wrap" v-if="show_orgtree">
            <el-tree
              ref="tree"
              node-key="orgId"
              :data="treeData"
              :props="treeProps"
              show-checkbox
              :expand-on-click-node="false"
              :default-checked-keys="modelForm.childrenOrgId"
              class="tree-box"
              icon-class="ivu-icon-ios-arrow-forward"
              @check-change="handleCheckChangeOrg"
              check-strictly="true"
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <div>
                  <embed
                    src="static\images\enterprise.svg"
                    width="10"
                    height="10"
                    type="image/svg+xml"
                    v-if="data.orgType == 1"
                    class="node-svg"
                  />
                  <embed
                    src="static\images\company.svg"
                    width="10"
                    height="10"
                    type="image/svg+xml"
                    v-if="data.orgType == 2"
                    class="node-svg"
                  />
                  <embed
                    src="static\images\department.svg"
                    width="10"
                    height="10"
                    type="image/svg+xml"
                    v-if="data.orgType == 10"
                    class="node-svg"
                  />
                  <span class="node-label">{{ node.label }}</span>
                </div>
              </span>
            </el-tree>
          </div>
        </Col>
        <Col span="12">
          <Form-item prop="assignmentType" :label="$t('module.role.assignmentType')">
            <Select
              v-model="modelForm.assignmentType"
              
              class="no-borderColor"
              @on-change="onAssignmentTypeChange"
              :transfer="true"
              :disabled="readOnly"
            >
              <Option
                v-for="items in assignmentTypeList"
                :value="items.vsiKey"
                :key="items.vsiKey"
              >{{ items.vsiValue }}</Option>
            </Select>
          </Form-item>
        </Col>
      </Row>
    </Form>
  </div>
</template>

<script>
import locales from "./locales.js";
import orgAssignRoleAPI from "@/api/orgAssignRoleAPI.js";
import valueSetAPI from "@/api/valueSetAPI.js";

const ASSIGNMENT_TYPE_ASSIGN_USER = "3";
export default {
  name: "DataAccess",
  mixins: [locales],
  props: {
    orgData: Array,
    roleId: String,
    roleName: String,
    orgName: String,
    orgId: String,
    dataAccess: Object,
    readOnly: {
      type: Boolean,
      default: false
    }
  },
  created: function() {
    this.setDialog();
    this.initManagementType();
    this.initAssignmentType();
    // 根据类型 - 是否显示tree
    if (this.dataAccess && this.dataAccess.managementType === "3") {
      this.show_orgtree = true;
    }
    // 分配模式为 指定用户 时
    if (this.dataAccess.assignmentType + "" == ASSIGNMENT_TYPE_ASSIGN_USER) {
      this.queryAssignedUser();
    }
  },
  data() {
    let buttons = [];
    if (!this.readOnly) {
      buttons.push({
        text: this.$t("common.save"),
        theme: "primary",
        handle: () => {
          this.save();
        },
        loading: false
      });
      buttons.push({
        text: this.$t("common.close"),
        handle: () => {
          this.$emit("Close");
        }
      });
    }
    // buttons.push({
    //   text: this.$t("common.close"),
    //   handle: () => {
    //     this.$emit("Close");
    //   }
    // });
    return {
      treeData: this.orgData,
      treeProps: {
        label: "orgName",
        children: "childrenDept",
        isLeaf: "isLeaf"
      },
      show_orgtree: false,
      managementTypeList: [], // 权限类型数据
      assignmentTypeList: [], // 用户分配模式数据
      modelForm: {
        orgId: this.orgId,
        roleId: this.roleId,
        managementType: this.dataAccess.managementType + "",
        assignmentType: this.dataAccess.assignmentType
          ? this.dataAccess.assignmentType + ""
          : ASSIGNMENT_TYPE_ASSIGN_USER,
        childrenOrgId: this.dataAccess.orgNodeVos
      },
      hasAssignedUser: false,
      rule: {
        managementType: [{ required: true }],
        assignmentType: [{ required: true }]
      },
      actions: buttons
    };
  },
  computed: {
    // isOrgDisabled() {
    //   return this.orgName !== "" && this.orgId !== "";
    // },
    isRoleDisabled() {
      return this.roleName !== "" && this.roleId !== "";
    }
  },
  methods: {
    // 设置弹窗信息
    setDialog() {
      if (this.readOnly) {
        this.$emit("SetTitle", this.$t("common.detail"));
      } else {
        this.$emit("SetTitle", this.$t("module.role.dataAccess"));
      }
      this.$emit("SetPageWidth", 710);
      this.$emit("SetPageMinHeight", 150);
      this.$emit("SetPageActions", this.actions);
    },
    // 初始化管理权限
    initManagementType() {
      valueSetAPI.getValueSetByCode("SYS_ROLE_DATA_TYPE").then(data => {
        if (data && data.length) {
          this.managementTypeList = data;
        }
      });
    },
    // 初始化用户分配模式
    initAssignmentType() {
      valueSetAPI.getValueSetByCode("SYS_ROLE_ASSIGNMENT_TYPE").then(data => {
        if (data && data.length) {
          this.assignmentTypeList = data;
        }
      });
    },
    queryAssignedUser() {
      let params = {
        commonPageDTO: { currentPage: 1, pageSize: 10 },
        condition: { orgId: this.orgId, roleId: this.roleId },
        pageNum: 1,
        pageSize: 10,
        sortDTO: { fieldName: "", orderBy: "" }
      };
      orgAssignRoleAPI.getAssignedUser(params).then(records => {
        if (records && records.length > 0) {
          this.hasAssignedUser = true;
        }
      });
    },
    // 保存数据
    save() {
      this.actions[0].loading = true;
      orgAssignRoleAPI
        .saveDataAccess(this.modelForm)
        .then(data => {
          this.$message.success({
            content: this.$t("common.saveSuccess"),
            duration: 3
          });
          this.$emit("Close", true);
        })
        .catch(err => {
          this.actions[0].loading = false;
          this.$message.error({
            content: this.$t("common.saveFailed"),
            duration: 3
          });
        });
    },
    // 操作下拉选项
    handleSelectDataAccess(value) {
      if (value == 3) {
        this.show_orgtree = true;
        this.modelForm.childrenOrgId = this.dataAccess.orgNodeVos;
      } else {
        this.show_orgtree = false;
        this.modelForm.childrenOrgId = [];
      }
    },
    onAssignmentTypeChange(value) {
      if (this.hasAssignedUser && value != ASSIGNMENT_TYPE_ASSIGN_USER) {
        let message = this.$t("module.role.warning.confirmDeleteRoleAssignedUser");
        this.$confirm
          .warning(message)
          .then(() => {})
          .catch(() => {
            this.modelForm.assignmentType = this.dataAccess.assignmentType + "";
          });
      }
      return false;
    },
    // 获取组织tree数据
    // loadData(node, resolve) {
    //   if (node.level === 0) {
    //     // 查询根节点
    //     this.setOrgRootNode(resolve);
    //   } else {
    //     orgAssignRoleAPI.queryOrgChildrenNode(node.data.orgId).then(children => {
    //       resolve(children);
    //     });
    //   }
    // },
    // 查询根节点
    // setOrgRootNode(resolve) {
    // orgAssignRoleAPI.queryOrgRootNode().then(children => {
    //     console.log("children:", children)
    //     resolve(children);
    // });
    //   resolve(this.orgData);
    // },
    // 操作Tree
    handleCheckChangeOrg(data, checked, indeterminate) {
      if (checked) {
        if (this.modelForm.childrenOrgId.indexOf(data.orgId) === -1) {
          this.modelForm.childrenOrgId.push(data.orgId);
        }
      } else {
        this.modelForm.childrenOrgId.some((item, i) => {
          if (item === data.orgId) {
            this.modelForm.childrenOrgId.splice(i, 1);
            return true;
          }
        });
      }
    }
  }
};
</script>

<style lang="less" scoped>
.org-tree-wrap {
  padding-left: 82px;
  .node-svg {
    position: relative;
    top: 1px;
  }
  .node-label {
    margin-left: 3px;
  }
}
</style>
